package day07;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;

public class StreamTest01 {

    private static List<Person> list = Person.list();

    public static void main(String[] args) {
        test8();
    }

    // 筛选与切片
    protected static void test1() {
        list.stream().filter(e -> e.getAge() > 123).forEach(System.out::println);
    }

    // 截流
    protected static void test2() {
        list.stream().limit(3).forEach(System.out::println);
    }

    protected static void test3() {
        list.stream().skip(1).forEach(System.out::println);
    }

    // 筛选(hashCode和equals)
    protected static void test4() {
        list.stream().distinct().forEach(System.out::println);
    }

    // map()
    protected static void test5() {
        Stream<String> stringStream = list.stream().map(Person::getName);
        stringStream.filter(p -> p.length() > 3).forEach(System.out::println);
    }

    // floatMap
    protected static void test6() {
        List<String> list = Arrays.asList("aa", "bb", "cc");
        // 使用map
        Stream<Stream<Character>> streamStream = list.stream().map(StreamTest01::fromStringToStream);
        streamStream.forEach(s -> {
            s.forEach(System.out::println);
        });

        System.out.println("*************************");

        // 使用flatMap
        Stream<Character> characterStream = list.stream().flatMap(StreamTest01::fromStringToStream);
        characterStream.forEach(System.out::println);

    }

    protected static Stream<Character> fromStringToStream(String string) {
        List<Character> list = new ArrayList<>();
        for (Character c : string.toCharArray()) {
            list.add(c);
        }
        return list.stream();
    }

    // 自然排序
    protected static void test7() {
        List<Integer> integers = Arrays.asList(23, 12, 44, 221, -20, 23);
        integers.stream().sorted().forEach(System.out::println);
    }

    // 比较器排序
    protected static void test8() {
//        list.stream().sorted((p1, p2) -> p1.getAge() - p2.getAge()).forEach(System.out::println);
        list.stream().sorted(Comparator.comparingInt(Person::getAge)).forEach(System.out::println);
    }
}
